package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.Report;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanExpressionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WorkSpaceService workSpaceService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverReport(LocalDate begin, LocalDate end) {
        List<String> localDates = new ArrayList<>();
        List<String> doubleList = new ArrayList<>();

        while (!begin.isAfter(end)) {
            //遍历日期加入到集合中
            localDates.add(String.valueOf(begin));

            //获取当天的开始时间和结束时间并根据时间和状态查询订单数据
            LocalDateTime zero = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime twelve = LocalDateTime.of(begin, LocalTime.MAX);
            Double turnover = orderMapper.getTurnover(zero, twelve, Orders.COMPLETED);

            //一定要判断是不是为空
            turnover = turnover == null ? 0.0 : turnover;

            //将营业额加入到营业额表中
            doubleList.add(String.valueOf(turnover));

            begin = begin.plusDays(1);
        }

        //将集合中所有元素组成字符串
        String dateList = String.join(",", localDates);
        String turnoverList = String.join(",", doubleList);

        //返回营业额统计回显对象
        return new TurnoverReportVO(dateList, turnoverList);
    }

    /**
     * 用户统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userReport(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        while (!begin.isAfter(end)) {
            dateList.add(begin);

            LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(begin, LocalTime.MAX);

            Integer totalUser = userMapper.count(new Report());
            Integer newUser = userMapper.count(Report.builder().beginTime(beginTime).endTime(endTime).build());

            totalUserList.add(totalUser);
            newUserList.add(newUser);

            begin = begin.plusDays(1);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    /**
     * 订单统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderReport(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        while (!begin.isAfter(end)) {
            dateList.add(begin);

            LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(begin, LocalTime.MAX);
            Integer orderCount = orderMapper.count(Report.builder().beginTime(beginTime).endTime(endTime).build());
            orderCountList.add(orderCount);

            Integer validOrderCount = orderMapper.count(new Report(beginTime, endTime, Orders.COMPLETED));
            validOrderCountList.add(validOrderCount);

            begin = begin.plusDays(1);
        }

        Integer totalOrderCount = orderMapper.count(new Report()) == null ? 0 : orderMapper.count(new Report());
        Integer validOrderCount = orderMapper.count(Report.builder().Status(Orders.COMPLETED).build()) == null ? 0 : orderMapper.count(Report.builder().Status(Orders.COMPLETED).build());

        Double orderCompletionRate = null;
        if (totalOrderCount == 0) {
            orderCompletionRate = 0.0;
        }
        orderCompletionRate = Double.valueOf(validOrderCount) / Double.valueOf(totalOrderCount);

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量前十商品统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO salesTop10Report(LocalDate begin, LocalDate end) {
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();

        Report report = Report.builder()
                .beginTime(LocalDateTime.of(begin, LocalTime.MIN))
                .endTime(LocalDateTime.of(end, LocalTime.MAX))
                .Status(Orders.COMPLETED)
                .build();
        List<GoodsSalesDTO> goodsSalesDTOList = orderDetailMapper.getSalesTop10(report);

        //map是映射，把集合中的一个元素映射到另一种类型的元素
//        List<String> names = goodsSalesDTOList.stream().map(goodsSalesDTO -> goodsSalesDTO.getName()).collect(Collectors.toList());
        nameList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        //map是映射，把集合中的一个元素映射到另一种类型的元素
//        numberList = goodsSalesDTOList.stream().map(goodsSalesDTO -> goodsSalesDTO.getNumber()).collect(Collectors.toList());
        numberList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 导出运营数据报表
     *
     * @param httpServletResponse
     */
    @Override
    public void exportBusinessData(HttpServletResponse httpServletResponse) {
        try {
            //获取inputStream流，将运营数据报表模版新建到Excel表
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

            assert inputStream != null;
            XSSFWorkbook  excel = new XSSFWorkbook(inputStream);


            //获取三十日的起始和结束日期，并写到表中
            LocalDate endDate = LocalDate.now().minusDays(1);
            LocalDate beginDate = LocalDate.now().minusDays(30);

            XSSFSheet sheet = excel.getSheet("Sheet1");

            XSSFRow row = sheet.getRow(1);

            row.getCell(1).setCellValue("时间：" + beginDate + "至" + endDate);

            //根据日期范围查询概览数据并写入到表中
            BusinessDataVO businessDataVO = workSpaceService.businessData(LocalDateTime.of(beginDate, LocalTime.MIN), LocalDateTime.of(endDate, LocalTime.MAX));

            row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());

            //根据日期范围查询明细数据并写入到表中
            int count = 0;
            while (!beginDate.isAfter(endDate)) {
                businessDataVO = workSpaceService.businessData(LocalDateTime.of(beginDate, LocalTime.MIN), LocalDateTime.of(beginDate, LocalTime.MAX));

                row = sheet.getRow(7 + count);
                row.getCell(1).setCellValue(String.valueOf(beginDate));
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());

                beginDate = beginDate.plusDays(1);
                count++;
            }

            //输出流到前端浏览器
            ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
            excel.write(servletOutputStream);

            //释放资源
            servletOutputStream.close();
            inputStream.close();
            excel.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
